package cn.wgx.commons.storage.filetool;

import cn.wgx.commons.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.UUID;

public class FileUploadTool {
    private static Logger logger = LoggerFactory.getLogger(FileUploadTool.class);

    // 文件允许格式
    private static String[] allowFiles = {".rar", ".doc", ".docx", ".zip", ".pdf", ".txt", ".swf", ".xlsx", ".gif",
            ".png", ".jpg", ".jpeg", ".bmp", ".xls", ".mp4", ".flv", ".ppt", ".avi", ".mpg", ".wmv", ".3gp", ".mov",
            ".asf", ".asx", ".vob", ".wmv9", ".rm", ".rmvb"};
    // 允许转码的视频格式（ffmpeg）
    private static String[] allowFLV = {".avi", ".mpg", ".wmv", ".3gp", ".mov", ".asf", ".asx", ".vob"};
    // 允许的视频转码格式(mencoder)
    private static String[] allowAVI = {".wmv9", ".rm", ".rmvb"};

    public static String PATH_TEMP;


    public static String getTmpPath() {
        if (PATH_TEMP == null) {
            PATH_TEMP = System.getProperty("java.io.tmpdir") + "cgtemp" + File.separator;
            File file = new File(PATH_TEMP);
            if (!file.exists()) {
                file.mkdirs();
            }
            logger.info("上传文件临时目录: " + PATH_TEMP);
        }
        return PATH_TEMP;
    }

    /**
     * 保存文件至临时目录
     *
     * @param file
     * @return
     */
    public static File saveToTempFolder(MultipartFile file) {
        String ext = StringUtils.getFileExt(file.getOriginalFilename());
        String uuid = UUID.randomUUID().toString();
        String tmpDir = getTmpPath() + uuid + File.separator;
        File dir = new File(tmpDir);
        dir.mkdirs();
        String newFileName = null;
        try {
            newFileName = tmpDir + uuid + "." + ext;
            File newFile = new File(newFileName);
            file.transferTo(newFile);
            return newFile;
        } catch (IOException e) {
            logger.error("FileUploadTool :保存错误 " + newFileName);
            return null;
        }
    }

    public static boolean delFile(File f) {
        if (f != null && f.exists()) {
            if (f.isFile()) {
                return f.delete();
            } else {
                File[] files = f.listFiles();
                if (files != null) {
                    int n = files.length;
                    for (int i = 0; i < n; i++) {
                        delFile(files[i]);
                    }
                }
                return f.delete();
            }
        }
        return false;

    }

    public static boolean delFile(String filePath) {
        if (filePath != null && filePath.startsWith(System.getProperty("java.io.tmpdir"))) {
            File f = new File(filePath);
            return delFile(f);
        }
        return false;
    }

    /**
     * 文件大小，返回KB、MB
     *
     * @return
     */
    private String getSize(File file) {
        String size = "";
        long fileLength = file.length();
        DecimalFormat df = new DecimalFormat("#.00");
        if (fileLength < 1024) {
            size = df.format((double) fileLength) + "BT";
        } else if (fileLength < 1048576) {
            size = df.format((double) fileLength / 1024) + "KB";
        } else if (fileLength < 1073741824) {
            size = df.format((double) fileLength / 1048576) + "MB";
        } else {
            size = df.format((double) fileLength / 1073741824) + "GB";
        }
        return size;
    }

    public static void main(String a[]) {
        System.out.println(getTmpPath());
    }

}